package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;

import cn.com.dashihui.web.dao.City;

public class CityService {
	
	public boolean sortCity(Map<String,String> sortMap){
		int batchSize = sortMap.size();
		List<String> sqlList = new ArrayList<String>();
		for(String id : sortMap.keySet()){
			sqlList.add("UPDATE t_dict_city SET orderNo="+sortMap.get(id)+" WHERE id="+id);
		}
		int[] result = Db.batch(sqlList,batchSize);
		return result.length>0;
	}
	
	public boolean addCity(City newObject){
		return newObject.save();
	}
	
	public boolean delCity(int id){
		City city = findById(id);
		List<String> sqlList = new ArrayList<String>();
		//删除相应记录
		sqlList.add("DELETE FROM t_dict_city WHERE id="+id);
		if(city.getInt("type")==2){
			//当前要删除记录如果是地市，则需要将其下属县/区
			sqlList.add("DELETE FROM t_dict_city WHERE parentid="+id);
		}else if(city.getInt("type")==1){
			//当前要删除记录如果是省份，则需要将其下属地市
			sqlList.add("DELETE FROM t_dict_city WHERE parentid="+id);
			//及其下属县/区
			List<City> cityList = City.me().find("SELECT * FROM t_dict_city WHERE parentid=?",id);
			if(cityList!=null){
				for(City item : cityList){
					sqlList.add("DELETE FROM t_dict_city WHERE parentid="+item.getInt("id"));
				}
			}
		}
		Db.batch(sqlList, sqlList.size());
		return true;
	}
	
	public boolean editCity(City object){
		return object.update();
	}
	
	public City findById(int id){
		return City.me().findFirst("SELECT * FROM t_dict_city WHERE id=?",id);
	}
	
	public City findByCode(String code){
		return City.me().findFirst("SELECT * FROM t_dict_city WHERE code=?",code);
	}
	
	public List<City> findAllCitys(){
		return trim(City.me().find("SELECT * FROM t_dict_city c ORDER BY c.parentid,c.orderNo"));
	}
	
	/**
	 * 将查询出来的地市列表，整理成嵌套形式
	 */
	private List<City> trim(List<City> cityList){
		if(cityList!=null){
			List<City> cityType1List = new ArrayList<City>(), cityType2List = new ArrayList<City>(), cityType3List = new ArrayList<City>();
			for(City city : cityList){
				if(city.getInt("type")==1){
					cityType1List.add(city);
				}else if(city.getInt("type")==2){
					cityType2List.add(city);
				}else if(city.getInt("type")==3){
					cityType3List.add(city);
				}
			}
			if(cityType3List.size()!=0){
				for(City r3 : cityType3List){
					for(City r2 : cityType2List){
						if(r3.getInt("parentid").intValue()==r2.getInt("id").intValue()){
							r2.addChild(r3);
							break;
						}
					}
				}
			}
			if(cityType2List.size()!=0){
				for(City r2 : cityType2List){
					for(City r1 : cityType1List){
						if(r2.getInt("parentid").intValue()==r1.getInt("id").intValue()){
							r1.addChild(r2);
							break;
						}
					}
				}
			}
			return cityType1List;
		}
		return null;
	}
}
